<?php
namespace app\web\controller;
use app\common\controller\Api;
use app\common\model\Daily as DailyModel;
use Carbon\Carbon;
use think\Db;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Integral extends Home
{
    public $noNeedLogin = [];


    /**
     * 我的积分
     */
    public function lists(){
        if($this->request->isGet()){
            $getData = $this->request->get();
            if(empty($getData['limit']) || empty($getData['check']) || empty($getData['num_type'])){
                $this->result('缺少必要参数', '', 204);
            }
            if(empty($getData['page'])){
                $getData['page'] = '1';
            }
            $userInfo = $this->userInfo;
            $data = Db::name('qt_integral_log')
                ->where(['user_id'=>$userInfo['id'],'check'=>$getData['check'],'num_type'=>$getData['num_type']])
                ->order('id desc')
                ->paginate($getData['limit']);
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 我需要审核的福利分
     */
    public function examine(){
        if($this->request->isGet()){
            $getData = $this->request->get();
            if(empty($getData['limit']) || empty($getData['time']) ){
                $this->result('缺少必要参数', '', 204);
            }
            if(empty($getData['page'])){
                $getData['page'] = '1';
            }
            if(isset($getData['time'])){
                $startDay =  $getData['time'].'-01';
                $startTime = strtotime($startDay);
                $time = explode('-',$getData['time']);
                $endDay = Carbon::create($time[0], $time[1])->endOfMonth()->toDateTimeString();
                $nowTime = date('Y-m-d H:i:s');
                if($nowTime < $endDay){
                    $endDay = $nowTime;
                }
                $endTime = strtotime($endDay);
                //查询数据
                $userInfo = $this->userInfo;
                $data = Db::name('qt_integral')
                    ->field('id,daily_first_id,user_id,daily_secede_id,created_time,daily_third_id,type,check,status,created_user_id')
                    ->where(function($query){
                        $userInfo = $this->userInfo;
                        $where1 =['first_user_id','=',$userInfo['id']];
                        $where2 =['secede_user_id','=',$userInfo['id']];
                        $where3 =['third_user_id','=',$userInfo['id']];
                        $query->table('dp_qt_examine')->whereOr([$where1,$where2,$where3]);
                    },'exists')
                    ->whereBetweenTime('created_time',$startTime,$endTime)
                    ->order('id desc')
                    ->paginate($getData['limit'])->each(function ($item){
                        $item['first_name'] = Db::name('qt_daily_type')->where('id',$item['daily_first_id'])->value('name');
                        $dailyRes = Db::name('qt_daily_type')->where('id',$item['daily_secede_id'])->find();
                        $item['secede_name'] = $dailyRes['name'];
                        $item['secede_num'] = $dailyRes['num'];
                        $item['created_user'] = Db::name('qt_users')->where('id',$item['created_user_id'])->value('nickname');
                        $item['third_name'] = Db::name('qt_daily_type')->where('id',$item['daily_third_id'])->value('name');
                        return $item;
                    });

                $this->result('查询成功', $data, 200);

            }
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 福利分值详情
     */
    public function detail(){
        if($this->request->isGet()){
            $getData = $this->request->get();
            if(empty($getData['id']) || empty($getData['id']) ){
                $this->result('缺少必要参数', '', 204);
            }
            $data = Db::name('qt_integral')->where(['id'=>$getData['id']])->find();
            //处理图片
            if(!empty($data['img'])){
                $image = explode(',',$data['img']);
                foreach ($image as $key=>$value){
                    $image[$key] = get_img_path($value);
                }
                $data['img'] = $image;
            }
            $userNames = [];
            //处理姓名
            if(!empty($data['user_id'])){
                $userIds = explode(',',$data['user_id']);
                foreach ($userIds as $key=>$value){
                    $userRes =  Db::name('qt_users')->where(['id'=>$value])->find();
                    if(empty($userRes['nickname'])){
                        $userNames[$key] = $userRes['phone'];
                    }else{
                        $userNames[$key] = $userRes['nickname'];
                    }
                }
            }
            $data['user_name'] = $userNames;
            $data['first_name'] = Db::name('qt_daily_type')->where('id',$data['daily_first_id'])->value('name');
            $dailyRes = Db::name('qt_daily_type')->where('id',$data['daily_secede_id'])->find();
            $data['secede_name'] = $dailyRes['name'];
            $data['secede_num'] = $dailyRes['num'];
            $data['third_name'] = Db::name('qt_daily_type')->where('id',$data['daily_third_id'])->value('name');
            $this->result('请求成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 我发布的福利分
     */
    public function my(){
        if($this->request->isGet()){
            $getData = $this->request->get();
            if(empty($getData['limit']) || empty($getData['time']) ){
                $this->result('缺少必要参数', '', 204);
            }
            if(empty($getData['page'])){
                $getData['page'] = '1';
            }
            if(isset($getData['time'])){
                $startDay =  $getData['time'].'-01';
                $startTime = strtotime($startDay);
                $time = explode('-',$getData['time']);
                $endDay = Carbon::create($time[0], $time[1])->endOfMonth()->toDateTimeString();
                $nowTime = date('Y-m-d H:i:s');
                if($nowTime < $endDay){
                    $endDay = $nowTime;
                }
                $endTime = strtotime($endDay);
                //查询数据
                $userInfo = $this->userInfo;
                $data = Db::name('qt_integral')
                    ->field('id,daily_first_id,daily_secede_id,daily_third_id,created_time,type,check,status')
                    ->where(['created_user_id'=>$userInfo['id']])
                    ->whereBetweenTime('created_time',$startTime,$endTime)
                    ->order('id desc')
                    ->paginate($getData['limit'])->each(function ($item){
                        $item['first_name'] = Db::name('qt_daily_type')->where('id',$item['daily_first_id'])->value('name');
                        $dailyRes = Db::name('qt_daily_type')->where('id',$item['daily_secede_id'])->find();
                        $item['secede_name'] = $dailyRes['name'];
                        $item['secede_num'] = $dailyRes['num'];
                        $item['third_name'] = Db::name('qt_daily_type')->where('id',$item['daily_third_id'])->value('name');
                        return $item;
                    });
                $this->result('查询成功', $data, 200);

            }
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 增加福利分
     */
    public function add(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            $validate = new \app\api\validate\Integral();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            if(empty($getData['secede_user_id'])){
                $getData['secede_user_id'] = null;
            }
            if(empty($getData['third_user_id'])){
                $getData['third_user_id'] = null;
            }
            if(empty($getData['cc_user_id'])){
                $getData['cc_user_id'] = null;
            }
            $userInfo = $this->userInfo;
            $getData['created_user_id'] = $userInfo['id'];
            $getData['group_id'] = $userInfo['group_id'];
            $getData['created_time'] = time();
            $integralId = Db::name('qt_integral')->insertGetId($getData);
            if($integralId){
                $this->result('添加成功', '', 200);
            }else{
                $this->result('添加失败', '', 204);
            }
//            $find = Db::name('qt_integral')
//                ->where('id',$integralId)->find();
//            $this->give($find);
//            $this->log($find['id'],$userInfo['id'],'2','');
//            Db::name('qt_integral')->where('id',$integralId)->update(['status'=>'2']);
//            $this->log($find['id'],$userInfo['id'],'3','');
        }
        $this->result('无效的请求', '', 204);
    }




    /**
     * 排行榜
     */
    public function ranking(){
        if($this->request->isGet()){
            $getData = $this->request->get();
            if($getData['num_type'] == '1'){
                $order = 'fraction_a desc';
                $field = 'id,nickname,avatar,fraction_a as fraction';
            }elseif ($getData['num_type'] == '2'){
                $order = 'fraction_b desc';
                $field = 'id,nickname,avatar,fraction_b as fraction';
            }elseif ($getData['num_type'] == '3'){
                $order = 'fraction_c desc';
                $field = 'id,nickname,avatar,fraction_c as fraction';
            }
            $data = Db::name('qt_users')
                ->field($field)
                ->where(['status'=>'0'])
                ->order($order)
                ->limit('10')->select();
            foreach ($data as $key=>$value) {
                $data[$key]['avatar'] = get_img_path($value['avatar']);
                $data[$key]['time'] = date('Y-m-d');
            };
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 审批福利分
     */
    public function save(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['id']) || empty($getData['type']) ){
                $this->result('缺少参数', '', 204);
            }
            $userInfo = $this->userInfo;
            $find = Db::name('qt_integral')
                ->where('id',$getData['id'])
                ->find();
            Db::name('qt_integral')
                ->where('id',$getData['id'])
                ->update(['user_id'=>$getData['user_id']]);
            $find['user_id'] = $getData['user_id'];
            if($find['first_user_id'] ==$userInfo['id']  || $find['secede_user_id'] ==$userInfo['id'] || $find['third_user_id'] ==$userInfo['id']){
                if($find['status'] != '1'){
                    $this->result('该项目已经审批过了', '', 204);
                }
                //一人审批
                if (empty($find['secede_user_id']) && empty($find['third_user_id'])){
                    //同意审批
                    if($getData['type'] == '1'){
                        $this->give($find);
                        $this->log($find['id'],$userInfo['id'],'2','');
                        $updata = Db::name('qt_integral')->where('id',$getData['id'])->update(['status'=>'2','explain'=>$getData['content']]);
                        if($updata !== false){
                            $this->result('审批成功','',200);
                        }
                        $this->log($find['id'],$userInfo['id'],'3','');
                        $this->result('审批失败','',204);
                    }
                    //拒绝审批
                    if($getData['type'] == '2'){
                        $updata = Db::name('qt_integral')->where('id',$getData['id'])->update(['status'=>'3','explain'=>$getData['content']]);
                        if($updata !== false){
                            $this->log($find['id'],$userInfo['id'],'3','');
                            $this->result('审批被拒绝','',200);
                        }
                        $this->result('审批失败','',204);
                    }
                }elseif(!empty($find['secede_user_id']) && empty($find['third_user_id'])){
                    //两人审批
                    //查询第一人是否审批
                    $firstRes = Db::name('qt_integral_log')->where('user_id',$find['first_user_id'])->find();
                    if(empty($firstRes)){
                        $this->result('前面有人没有审批哦','',204);
                    }
                    if($firstRes['type'] == '2'){
                        Db::name('qt_integral')->where('id',$getData['id'])->update(['status'=>'3','explain'=>$getData['content']]);
                        $this->log($find['id'],$userInfo['id'],'3','');
                        $this->result('审批已经被拒绝','',204);
                    }
                    //开始审批
                    $this->give($find);
                    $updata = Db::name('qt_integral')->where('id',$getData['id'])->update(['status'=>'2','explain'=>$getData['content']]);
                    if($updata !== false){
                        $this->log($find['id'],$userInfo['id'],'2','');
                        $this->result('审批成功','',200);
                    }
                    $this->log($find['id'],$userInfo['id'],'3','');
                    $this->result('审批失败','',204);
                }elseif(!empty($find['secede_user_id']) && !empty($find['third_user_id'])){
                    //三人审批
                    //查询第一人是否审批
                    $firstRes = Db::name('qt_integral_log')->where('user_id',$find['first_user_id'])->find();
                    $secedeRes = Db::name('qt_integral_log')->where('user_id',$find['secede_user_id'])->find();
                    //检测第一人审批状态
                    if(empty($firstRes)){
                        $this->result('前面有人没有审批哦','',204);
                    }
                    if($firstRes['type'] == '2'){
                        $this->log($find['id'],$userInfo['id'],'3','');
                        Db::name('qt_integral')->where('id',$getData['id'])->update(['status'=>'3','explain'=>$getData['content']]);
                        $this->result('审批已经被拒绝','',204);
                    }
                    //检测第二人审批状态
                    if(empty($secedeRes)){
                        $this->result('前面有人没有审批哦','',204);
                    }
                    if($secedeRes['type'] == '2'){
                        $this->log($find['id'],$userInfo['id'],'3','');
                        Db::name('qt_integral')->where('id',$getData['id'])->update(['status'=>'3','explain'=>$getData['content']]);
                        $this->result('审批已经被拒绝','',204);
                    }
                    $this->give($find);
                    $updata = Db::name('qt_integral')->where('id',$getData['id'])->update(['status'=>'2','explain'=>$getData['content']]);
                    if($updata !== false){
                        $this->log($find['id'],$userInfo['id'],'2','');
                        $this->result('审批成功','',200);
                    }
                    $this->result('审批失败','',204);
                }
                $this->result('审批成功', '', 200);
            }else{
                $this->result('您没有审批的权限', '', 204);
            }
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 给用户增加积分
     */
    public function give($data){
        $userIds = json_decode($data['user_id'],true);
        $daily = Db::name('qt_daily_type')->where('id',$data['daily_first_id'])->value('name');
        $son_daily = Db::name('qt_daily_type')->where('id',$data['daily_secede_id'])->value('name');
        foreach ($userIds as $key=>$value){
            $insert[$key]['user_id'] = $value['user_id'];
            $insert[$key]['fraction'] = $value['num'];
            $insert[$key]['daily'] = $daily;
            $insert[$key]['son_daily'] = $son_daily;
            $insert[$key]['check'] = $data['check'];
            $insert[$key]['num_type'] = $data['type'];
            $insert[$key]['type'] = '3';
            $insert[$key]['created_time'] = time();
            if($data['num_type'] =  '1'){
                $inc = 'fraction_a';
            }
            if($data['num_type'] =  '2'){
                $inc = 'fraction_b';
            }
            if($data['check'] == '1'){
                //加分
                Db::name('qt_users')->where('id',$value['user_id'])->setInc($inc,$value['num']);
            }else {
                //减分
                Db::name('qt_users')->where('id', $value['user_id'])->setDec($inc, $value['num']);
            }
        }
        Db::name('qt_integral_log')->insertAll($insert);

    }

    /**
     * 处理用户A分
     */
    public function handle_first(){
        //查询用户上一个月的A分
        $startTime = date('Y-m-01 00:00:00', strtotime('-1 month'));
        $endTime = date('Y-m-t 24:00:00', strtotime('-1 month'));
        $userId = '3';
        $data = Db::name('qt_integral_log')
            ->where(['user_id'=>$userId,'num_type'=>'1'])
            ->whereTime('created_time','last month')
            ->select();
        static $total = 0;
        foreach ($data as $key=>$value){
            if($value['check'] == '1'){
                $total += $value['fraction'];
            }elseif ($value['check'] == '2'){
                $total -= $value['fraction'];
            }
        }
        //减去用户A分数增加C分
        Db::name('qt_users')->where('id',$userId)->setInc('fraction_c',$total);
        Db::name('qt_users')->where('id',$userId)->setDec('fraction_a',$total);
        foreach ($data as $key=>$value){
            Db::name('qt_integral_log')->where(['id'=>$value['id']])->update(['num_type'=>'3']);
        }
    }



    /**
     * 处理用户B分
     */
    public function handle_second(){
        //查询用户上一个季度的A分
        $month = date("m");
        if ($month >=1 && $month < 4)
        {
            $year = date("Y", strtotime("-1 year"));
            $startTime = date($year.'-10-01 00:00:00');
            $endTime =  date($year.'Y-12-31 24:00:00');
        }
        else if ($month >= 4 && $month < 7)
        {
            $startTime = date('Y-01-01 00:00:00');
            $endTime =  date('Y-03-31 24:00:00');
        }
        else if ($month >= 7 && $month < 10)
        {
            $startTime = date('Y-04-01 00:00:00');
            $endTime =  date('Y-06-30 24:00:00');
        }
        else
        {
            $startTime = date('Y-07-01 00:00:00');
            $endTime =  date('Y-09-30 24:00:00');
        }
        $userId = '3';
        $data = Db::name('qt_integral_log')
            ->where(['user_id'=>$userId,'num_type'=>'2'])
            ->whereTime('created_time','between',[$startTime,$endTime])
            ->select();
        static $total = 0;
        foreach ($data as $key=>$value){
            if($value['check'] == '1'){
                $total += $value['fraction'];
            }elseif ($value['check'] == '2'){
                $total -= $value['fraction'];
            }
        }
        //减去用户A分数增加C分
        Db::name('qt_users')->where('id',$userId)->setInc('fraction_c',$total);
        Db::name('qt_users')->where('id',$userId)->setDec('fraction_b',$total);
        foreach ($data as $key=>$value){
            Db::name('qt_integral_log')->where(['id'=>$value['id']])->update(['num_type'=>'3']);
        }
    }



    public function log($id,$userId,$status,$content){
        $logData['integral_id'] = $id;
        $logData['user_id'] = $userId;
        $logData['status'] = $status;
        $logData['content'] = $content;
        Db::name('qt_integral_user')->insert($logData);
    }

}
